import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    TextInput,
    TouchableOpacity,
    Modal
} from 'react-native';
import Swiper from 'react-native-swiper';
import { MarqueeHorizontal, MarqueeVertical } from 'react-native-marquee-ab';
import Styles from './Styles';


import app from '../../../app.json';
import Ugame from '../../../Ugame';
import Httpc from "../../utils/Httpc";
import REQUEST from "../../../REQUEST";
import Football from "../../utils/Football";
import Utils from "../../utils/Utils";

const { width, height } = Dimensions.get('window')

export default class FootballBonusOpt extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            refreshing: false,
            toastModelVisible: false,
            message: '',
            is_need_pictures: true,//是否需要上传图片
            opt_status: false,
            beishuInput: "1",//倍数

            type: 1,//1奖金平均，2博热保本 3奖金最高

            title: '',
            betNumber: [],
            betRecords: [],
            bet_count: 0,
            min_bet_amount: 0,
            bet_amount: 0,
            bet_min_bonus: 0,
            bet_max_bonus: 0,
            name: null,
            isPhoto: 0,

            is_bet: false,
            is_tips: false,
        };
        this.betRecordsSource = null;
    }
    static navigationOptions = {
        title: '奖金优化',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: '#d0162e',
            paddingTop: 18,
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            //fontWeight: 'bold',
        },
    }
    componentDidMount() {
        const { navigation } = this.props;
        let postBetData = navigation.getParam("postBetData");
        console.log(postBetData);
        this.betRecordsSource = Utils.deepCopy(postBetData.betRecords);
        this.setState({
            title: postBetData.title,
            betNumber: postBetData.betNumber,
            betRecords: Utils.deepCopy(postBetData.betRecords),
            name: postBetData.name,
            isPhoto: postBetData.isPhoto,
            bet_amount: postBetData.bet_amount,
            min_bet_amount: postBetData.betRecords.length * 2
        }, () => {
            this._createLists();
        })

    }
    _createLists = () => {
        let betRecords = this.state.betRecords;
        for (let i = 0; i < betRecords.length; i++) {
            this.betRecordsSource[i].index = i;
            this.betRecordsSource[i].show = 'off';
            betRecords[i].index = i;
            betRecords[i].show = 'off';
        }
        this._do_auto_assign();
        this._compute_bonus();
    }
    _compute_bonus = () => {
        let betRecords = this.state.betRecords;
        let bet_min_bonus = 0;
        let bet_max_bonus = 0;
        for (let i = 0; i < betRecords.length; i++) {
            let odds = Number(betRecords[i].odds * betRecords[i].multNum);
            if (odds == 0) {
                continue;
            }
            if (bet_min_bonus == 0) {
                bet_min_bonus = odds;
            } else {
                if (odds < bet_min_bonus) {
                    bet_min_bonus = odds;
                }
            }
            bet_max_bonus += Number(odds);
        }
        this.setState({
            is_bet: true,
            bet_min_bonus: Number(bet_min_bonus).toFixed(2),//最少奖金
            bet_max_bonus: Number(bet_max_bonus).toFixed(2),//最大奖金 
        });
    }
    _on_reduce_multNum = (index) => {
        let betRecords = this.state.betRecords;
        if (betRecords[index].multNum == 0) {
            return;
        }
        betRecords[index].multNum = betRecords[index].multNum - 1;
        this.setState({
            betRecords: betRecords
        }, () => {
            this._compute_bonus();
        });
    }
    _on_increase_multNum = (index) => {
        let betRecords = this.state.betRecords;
        betRecords[index].multNum = betRecords[index].multNum + 1;
        this.setState({
            betRecords: betRecords
        }, () => {
            this._compute_bonus();
        });
    }
    _on_change_type = (type) => {
        if (type == 2 || type == 3) {
            let name = this.state.name;
            if (name.split(",").length > 1) {
                this.do_toast('此玩法不支持' + (type == 2 ? '博热保本' : '奖金最高'), 500);
                return;
            }
        }
        this.setState({
            type: type,
            is_bet: false,
            is_tips:false
        }, () => {
            this._do_auto_assign();
        });
    }
    renderBetNumberitem = ({ item, index }) => {
        return (
            <View style={Styles.item_tips_th}>
                <Text style={Styles.item_tips_td}>{item.week}{item.sort_num.slice(-3)}</Text>
                <Text style={Styles.item_tips_td}>{item.h_cn_abbr}</Text>
                <Text style={Styles.item_tips_td}>{item.a_cn_abbr}</Text>
                <Text style={Styles.item_tips_td}>{item.str} {item.odds}</Text>
            </View>
        );
    }
    _do_change_buyNumber_show = (index) => {
        let betRecords = this.state.betRecords;
        betRecords[index].show = betRecords[index].show == 'off' ? 'on' : 'off';
        this.setState({
            betRecords: betRecords
        });
    }
    _do_change_multNum = (index) => {
        let { betRecords, bet_amount } = this.state;
        let multNum = betRecords[index].multNum;
        let amount = 0;
        if (multNum > 0) {
            amount = multNum * 2;
            betRecords[index].multNum = 0;
            bet_amount = bet_amount - amount;
        } else {
            amount = 2;
            betRecords[index].multNum = 1;
            bet_amount = bet_amount + amount;
        }
        this.setState({
            betRecords: betRecords,
            bet_amount: bet_amount,
            is_bet: bet_amount > 0 ? true : false
        }, () => {
            this._compute_bonus()
        });
    }
    renderBetRecordsitem = ({ item, index }) => {
        let betNumber = item.buyNumberC.split("|");
        let buyNumber = [];
        for (let i = 0; i < betNumber.length; i++) {
            buyNumber.push(this.state.betNumber[betNumber[i]]);
        }
        return (
            <View>
                <View style={Styles.item}>
                    <TouchableOpacity onPress={() => { this._do_change_multNum(index) }}>
                        <View style={[Styles.item_td, { width: 60 }]}>
                            {item.multNum > 0 ?
                                <Image resizeMode="cover" source={require('../../image/js_img_icon_jiangjin_checked.png')} /> :
                                <Image resizeMode="cover" source={require('../../image/js_img_icon_jiangjin_unchecked.png')} />
                            }
                            <Text style={{ fontSize: 12, color: '#666666', marginLeft: 5 }}>{item.name}</Text>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={() => { this._do_change_buyNumber_show(index) }}>
                        <View style={[Styles.item_td_row, { width: width - 262 }]}>
                            <Text style={{ fontSize: 12, color: '#666666' }}>{buyNumber[0].h_cn_abbr}|{buyNumber[0].str}({buyNumber[0].odds})</Text>
                            <Text style={{ fontSize: 12, color: '#666666' }}>{buyNumber[1].h_cn_abbr}|{buyNumber[1].str}({buyNumber[1].odds})</Text>
                            <Image resizeMode="cover" style={{ marginTop: 5 }} source={require('../../image/js_img_icon_arrow_down.png')} />
                        </View>
                    </TouchableOpacity>
                    <View style={[Styles.item_td, { width: 100 }]}>
                        <View style={Styles.beishu}>
                            <View style={Styles.beishu_input}>
                                <TouchableOpacity onPress={() => this._on_reduce_multNum(index)}>
                                    <View style={{ padding: 5 }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_icon_subtract.png')} />
                                    </View>
                                </TouchableOpacity>
                                <TextInput
                                    style={Styles.textInput}
                                    value={item.multNum.toString()}
                                    keyboardType='numeric'
                                    onChangeText={(multNum) => this._onPhoneChangeText(index, multNum)}
                                />
                                <TouchableOpacity onPress={() => this._on_increase_multNum(index)}>
                                    <View style={{ padding: 5 }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_sub_icon_add.png')} />
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View >
                    </View>
                    <View style={[Styles.item_td, { width: 70 }]}>
                        <Text style={item.multNum > 0 ? Styles.textR : Styles.textD}>{(item.odds * item.multNum).toFixed(2)}</Text>
                    </View>
                </View>
                <View style={item.show == 'off' ? Styles.item_tips_hidden : Styles.item_tips}>
                    <Text style={Styles.item_tips_title}>组合方案</Text>
                    <View style={Styles.item_tips_th}>
                        <Text style={Styles.item_tips_td}>场次</Text>
                        <Text style={Styles.item_tips_td}>主队</Text>
                        <Text style={Styles.item_tips_td}>客队</Text>
                        <Text style={Styles.item_tips_td}>投注内容</Text>
                    </View>
                    <FlatList
                        data={buyNumber}
                        extraData={this.state}
                        keyExtractor={(item, index) => index.toString()}
                        renderItem={this.renderBetNumberitem}
                    />
                </View>

            </View>
        );
    }
    _onBetAmountChangeText = (bet_amount) => {
        let { min_bet_amount } = this.state;
        if (bet_amount == '' || Number(bet_amount) == 0 || isNaN(Number(bet_amount))) {
            if (bet_amount < min_bet_amount) {
                this.setState({
                    bet_amount: min_bet_amount
                });
                this.do_toast('不能少于' + min_bet_amount + "元", 1000);
                return;
            }
        }
        if (Number(bet_amount) > app.maxBetAmount) {
            this.do_toast('不能大于' + app.maxBetAmount + "元", 1000);
            return;
        }
        if (Number(bet_amount) % 2 !== 0) {
            this.do_toast('必须为偶数', 1000);
            return;
        }
        this.setState({
            bet_amount: bet_amount
        }, () => {
            this._do_auto_assign();
        });
    }
    _on_reduce_betAmount = () => {
        let { bet_amount, min_bet_amount, is_bet } = this.state;
        if (is_bet == false) {
            return;
        }
        bet_amount = Number(bet_amount) - 2;
        if (bet_amount < min_bet_amount) {
            this.do_toast('不能少于' + min_bet_amount + "元", 1000);
            return;
        }
        this.setState({
            bet_amount: bet_amount
        }, () => {
            this._do_auto_assign();
        });
    }
    _on_increase_betAmount = () => {
        let { bet_amount, min_bet_amount, is_bet } = this.state;
        if (is_bet == false) {
            return;
        }
        bet_amount = Number(bet_amount) + 2;
        if (bet_amount < min_bet_amount) {
            this.do_toast('不能少于' + min_bet_amount + "元", 1000);
            return;
        }
        if (bet_amount > app.maxBetAmount) {
            this.do_toast('不能大于' + app.maxBetAmount + "元", 1000);
            return;
        }
        this.setState({
            bet_amount: bet_amount
        }, () => {
            this._do_auto_assign();
        });
    }
    _do_auto_assign = () => {
        switch (this.state.type) {
            case 1:
                //平均分配
                this._on_average_assign();
                break;
            case 2:
                //博热保本
                this._on_borebaoben_assign();
                break;
            case 3:
                //奖金最高
                this._on_jjzg_assign();
                break;
        }
    }
    //平均分配
    _on_average_assign = () => {
        let { bet_amount } = this.state;
        let betRecords = Utils.deepCopy(this.betRecordsSource);

        let bet_count = betRecords.length;
        let i = bet_count * 2;
        for (; i < bet_amount; i += 2) {
            //倍率都+1取最小值
            let copyBetRecords = Utils.deepCopy(betRecords);
            copyBetRecords.sort(function (item1, item2) {
                return (item1.odds * (item1.multNum + 1)) - (item2.odds * (item2.multNum + 1));
            });
            let index = copyBetRecords[0].index;
            betRecords[index].multNum++;
        }
        this.setState({
            betRecords: betRecords,
            is_tips:this.isTipsState(betRecords)
        }, () => {
            this._compute_bonus();
        });
    }
    //博热保本
    _on_borebaoben_assign = () => {
        let { bet_amount } = this.state;
        let betRecords = Utils.deepCopy(this.betRecordsSource);
        let bet_count = betRecords.length;
        let i = sum_amount = bet_count * 2;
        for (; i <= bet_amount; i += 2) {
            let is_have = false;
            for (let j = 0; j < betRecords.length; j++) {
                if (betRecords[j].odds * betRecords[j].multNum >= bet_amount) {
                    continue;
                }
                betRecords[j].multNum++;
                sum_amount += 2;
            }
        }
        let left_amount = bet_amount - sum_amount;
        if (left_amount >= 0) {
            //剩余的分给最小赔率
            betRecords[0].multNum = betRecords[0].multNum + parseInt(left_amount / 2);
        }
        this.setState({
            betRecords: betRecords,
            is_tips:this.isTipsState(betRecords)
        }, () => {
            this._compute_bonus();
        });

    }
    isTipsState(betRecords){
        let {bet_amount}=this.state;
        let is_tips=false;
        if(betRecords.length * 2 == bet_amount){
            is_tips=true;
        }
        return is_tips;
    }
    //奖金最高
    _on_jjzg_assign = () => {
        let { bet_amount } = this.state;
        let betRecords = Utils.deepCopy(this.betRecordsSource);
        let bet_count = betRecords.length;
        let i = sum_amount = bet_count * 2;
        for (; i <= bet_amount; i += 2) {
            for (let j = 0; j < betRecords.length; j++) {
                if (betRecords[j].odds * betRecords[j].multNum >= bet_amount) {
                    continue;
                }
                betRecords[j].multNum++;
                sum_amount += 2;
            }
        }
        let left_amount = bet_amount - sum_amount;
        if (left_amount >= 0) {
            //剩余的分给最小赔率
            betRecords[betRecords.length - 1].multNum = betRecords[betRecords.length - 1].multNum + parseInt(left_amount / 2);
        }
        this.setState({
            betRecords: betRecords,
            is_tips:this.isTipsState(betRecords)
        }, () => {
            this._compute_bonus();
        });
    }
    do_bet_order = () => {
        let { title, name, betNumber, isPhoto, betRecords, bet_amount, min_bet_amount, is_bet } = this.state;
        if (is_bet == false) return;

        let beishuInput = this.state.beishuInput;
        if (beishuInput == '' || beishuInput < 1) {
            beishuInput = 1;
            this.setState({ beishuInput: '1' });
        }
        if (name.length == 0) {
            this.do_toast('请选择玩法', 500);
            return;
        }
        //单笔金额不能超过20万元
        if (bet_amount > app.maxBetAmount) {
            this.do_toast('单笔金额不能超过20万元', 500);
            return;
        }
        let betNumberTemp = [];
        for (let key in betNumber) {
            betNumber[key].NoID = betNumber[key].NoID.replace(/_/g, '');
            betNumberTemp.push(betNumber[key]);
        }
        // for (let i = 0; i < betRecords.length; i++) {
        //     delete betRecords[i].buyNumberC;
        // }
        var postBetData = {
            name: name,
            isPhoto: isPhoto,
            betNumber: betNumberTemp,
            betRecords: betRecords
        }
        //end
        postBetData.IsFollow = 0;
        postBetData.Title = title;
        postBetData.Commis = 0;
        postBetData.IsShow = 0;
        postBetData.Metro = '';
        postBetData.IsOptimize = 1;
        this.props.navigation.navigate('BetOrder', {
            type: 1,
            postBetData: postBetData,
            game_model: "FootballGame",
        })
    }
    do_toast = (str, time) => {
        this.setState({
            message: str,
            toastModelVisible: true
        });
        setTimeout(() => {
            this.setState({
                message: '',
                toastModelVisible: false
            });
        }, time);
    }
    toast = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.toastModelVisible}
                onRequestClose={() => {
                    this.setState({
                        toastModelVisible: false
                    });
                }}
            >
                <View style={{ flexDirection: 'row', justifyContent: 'center', position: 'absolute', bottom: 100, width: width }}>
                    <Text style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: '#ffffff', borderRadius: 10, height: 40, lineHeight: 40, paddingLeft: 20, paddingRight: 20 }}>{this.state.message}</Text>
                </View>
            </Modal>
        );
    }
    render() {
        let { is_tips, type, betRecords, bet_amount, bet_count, bet_min_bonus, bet_max_bonus, is_bet } = this.state;
        return (
            <View style={Styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                {is_tips ?
                    <Text style={Styles.is_tips}>资金优化无效果，请选择复式或增加位数</Text> :
                    null
                }
                <View style={Styles.header}>
                    <TouchableOpacity onPress={() => this._on_change_type(1)}>
                        <Text style={type == 1 ? Styles.header_item_on : Styles.header_item}>奖金平均</Text>
                    </TouchableOpacity>
                    <View style={{ width: 1, height: 30, backgroundColor: '#d0162e' }}></View>
                    <TouchableOpacity onPress={() => this._on_change_type(2)}>
                        <Text style={type == 2 ? Styles.header_item_on : Styles.header_item}>博热保本</Text>
                    </TouchableOpacity>
                    <View style={{ width: 1, height: 30, backgroundColor: '#d0162e' }}></View>
                    <TouchableOpacity onPress={() => this._on_change_type(3)}>
                        <Text style={type == 3 ? Styles.header_item_on : Styles.header_item}>奖金最高</Text>
                    </TouchableOpacity>
                </View>
                <View style={Styles.table_th}>
                    <Text style={[Styles.table_th_text, { width: 60 }]}>过关</Text>
                    <Text style={[Styles.table_th_text, { width: width - 262 }]}>单注组合</Text>
                    <Text style={[Styles.table_th_text, { width: 100 }]}>注数分布</Text>
                    <Text style={[Styles.table_th_text, { width: 70 }]}>预测奖金</Text>
                </View>
                <ScrollView style={{ height: 400 }}>
                    <View style={Styles.lists}>
                        <FlatList
                            data={betRecords}
                            extraData={this.state}
                            keyExtractor={(item, index) => index.toString()}
                            renderItem={this.renderBetRecordsitem}
                        />
                    </View>

                </ScrollView>
                <View style={[Styles.hide_opt]}>
                    <View style={Styles.bet_type}>
                        <View style={Styles.beishu}>
                            <Text style={{ fontSize: 12, color: '#999999' }}>计划购买</Text>
                            <View style={Styles.beishu_input}>
                                <TouchableOpacity onPress={() => this._on_reduce_betAmount()}>
                                    <View style={{ padding: 5 }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_icon_subtract.png')} />
                                    </View>
                                </TouchableOpacity>
                                <TextInput
                                    style={{ height: 25, padding: 0, lineHeight: 25, textAlign: 'center', width: 60, color: '#333333', fontSize: 12, borderLeftWidth: 1, borderRightWidth: 1, borderColor: '#cacaca' }}
                                    value={this.state.bet_amount.toString()}
                                    keyboardType='numeric'
                                    onChangeText={(bet_amount) => this._onBetAmountChangeText(bet_amount)}
                                />
                                <TouchableOpacity onPress={() => this._on_increase_betAmount()}>
                                    <View style={{ padding: 5 }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_sub_icon_add.png')} />
                                    </View>
                                </TouchableOpacity>
                            </View>
                            <Text style={{ fontSize: 12, color: '#999999' }}>元</Text>
                        </View >
                    </View>

                </View>
                <View style={Styles.yujijinge}>
                    <View style={Styles.yujijinge_sum}>
                        <Text style={{ fontSize: 12 }}>共</Text>
                        <Text style={{ fontSize: 12, color: '#d0162e' }}>{bet_amount}</Text>
                        <Text style={{ fontSize: 12 }}>元</Text>
                        <Text style={{ fontSize: 12 }}>预计奖金:</Text>
                        <Text style={{ fontSize: 12, color: '#d0162e' }}>{bet_min_bonus}</Text>
                        <Text style={{ fontSize: 12, color: '#d0162e' }}>~</Text>
                        <Text style={{ fontSize: 12, color: '#d0162e' }}>{bet_max_bonus}</Text>
                        <Text style={{ fontSize: 12 }}>元</Text>
                    </View>
                    <Text style={Styles.yujijinge_tips}>预计奖金参考，请以实票为准</Text>
                </View>
                {is_bet ?
                    <TouchableOpacity onPress={() => this.do_bet_order()}>
                        <View style={Styles.bottom}>
                            <View style={Styles.tuzhu}>
                                <Text style={{ color: '#ffffff' }}>确认投注</Text>
                            </View>
                        </View>
                    </TouchableOpacity> :
                    <View style={Styles.bottom}>
                        <View style={Styles.dtuzhu}>
                            <Text style={{ color: '#ffffff' }}>确认投注</Text>
                        </View>
                    </View>
                }
                {this.toast()}
            </View>
        )
    }



}
